package com.iotechn.unimall.admin.api.card;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.iotechn.unimall.core.exception.AdminServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.domain.*;
import com.iotechn.unimall.data.dto.CardDTO;
import com.iotechn.unimall.data.dto.UserCardDTO;
import com.iotechn.unimall.data.enums.CardUseType;
import com.iotechn.unimall.data.mapper.*;
import com.iotechn.unimall.data.model.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: kbq
 * Date: 2019-07-12
 * Time: 下午11:26
 */
@Service
public class AdminCardServiceImpl implements AdminCardService {

    @Autowired
    private CardMapper cardMapper;
    @Autowired
    private UserCardMapper userCardMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private StoreMapper storeMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CardDO addCard(Long adminId,String img, String title, String description, Integer total, Integer money, Integer source,Integer allStock) throws ServiceException {

        String cardNo = "GWLL" + (int) ((Math.random() * 9 + 1) * 100000);

        int type = 0;
        int limit = 0;
        int days = 0;
        int status = 1;
        int use = 0;

        CardDO cardDO = new CardDO(title, cardNo, img,type, description, total, total, limit, money, days, status, use, adminId, source,allStock);
        Date now = new Date();
        cardDO.setGmtCreate(now);
        cardDO.setGmtUpdate(now);
        cardDO.setCardUse(CardUseType.LOCK.getCode());
        if (cardMapper.insert(cardDO) > 0) {
            return cardDO;
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteCard(Long adminId, Long id) throws ServiceException {
        EntityWrapper wrapperC = new EntityWrapper();
        wrapperC.eq("id", id);
        if (cardMapper.delete(wrapperC) <= 0) {
            throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
        }
        EntityWrapper wrapperUC = new EntityWrapper();
        wrapperUC.eq("card_id", id);
        userCardMapper.delete(wrapperUC);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateCard(Long adminId, Long id, String title, String description, Integer total, Integer money) throws ServiceException {
        CardDO cardDO = new CardDO();
        cardDO.setId(id);
        cardDO.setTotal(total);
        cardDO.setTitle(title);
        cardDO.setDescription(description);
        cardDO.setMoney(money);
        Date now = new Date();
        cardDO.setGmtUpdate(now);
        return cardMapper.updateById(cardDO) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateCardStatus(Long adminId, Long id, Integer status) throws ServiceException {
        CardDO cardDO = new CardDO();
        cardDO.setId(id);
        cardDO.setStatus(status);
        cardDO.setGmtUpdate(new Date());
        return cardMapper.updateById(cardDO) > 0;
    }

    @Override
    public Page<CardDTO> queryCardByTitle(Long adminId, Integer source,String title, Integer type, Integer cardUse,String cardNo, Integer pageNo, Integer limit) throws ServiceException {
        EntityWrapper wrapper = new EntityWrapper();
        Date now = new Date();
        if (!StringUtils.isEmpty(title)) {
            wrapper.like("title", title);
        }
        if (type != null) {
            wrapper.eq("type", type);
        }
        if (cardUse != null) {
            if (cardUse >= 0 && cardUse < 2) {
                wrapper.eq("card_use", cardUse);
                // wrapper.andNew().gt("gmt_end", now).or().isNotNull("days"); //Card -> conpon.gt("gmt_end", now).or().isNotNull("days")
            } else if (cardUse < 0) {
                // wrapper.lt("gmt_end", now);
            } else {
                throw new AdminServiceException(ExceptionDefinition.CARD_CHECK_DATA_FAILED);
            }
        }
        List<Long> ids=new ArrayList<>();
        if(!StringUtils.isEmpty(cardNo)){
            List<UserCardDO> userCardDOS = userCardMapper.selectList(new EntityWrapper<UserCardDO>().eq("card_no", cardNo));
            for (UserCardDO card : userCardDOS
                    ) {
                ids.add(card.getCardId());
            }
            wrapper.in("id",ids);
        }
        Integer count = cardMapper.selectCount(wrapper);
        List<CardDTO> CardDTOList = cardMapper.getCardList(source,title, type, cardUse,ids, (pageNo - 1) * limit, limit);
        Page<CardDTO> page = new Page<CardDTO>(CardDTOList, pageNo, limit, count);
        return page;
    }

    @Override
    public Page<UserCardDTO> queryCardById(Long adminId, String cardNo, Long cardId,Integer cardStatus, Integer limit, Integer pageNo) {
        if(pageNo == null){
            return null;
        }
        if(pageNo > 0){
            pageNo = pageNo -1;
        }
        CardDO cardDO = cardMapper.selectById(cardId);
        CardDTO cardDTO = new CardDTO();
        BeanUtils.copyProperties(cardDO, cardDTO);
        List<UserCardDTO> userCardDTOList = new ArrayList<UserCardDTO>();
        Integer count =0;
        if (cardDO != null) {
            AdminDO adminDO = adminMapper.selectById(cardDO.getAdminId());
            if (adminDO != null) {
                cardDTO.setAdminName(adminDO.getUsername());
            }
            EntityWrapper wrapper = new EntityWrapper();
            if(!StringUtils.isEmpty(cardNo)){
                wrapper.eq("card_no",cardNo);
            }
            wrapper.eq("card_id", cardDO.getId());
            if(cardStatus != null){
                wrapper.eq("status",cardStatus);
            }
            count = userCardMapper.selectCount(wrapper);
            List<UserCardDO> userCardDOList = userCardMapper.selectUserCardDOsPage(cardNo,cardDO.getId(),cardStatus,limit,(pageNo * limit -1) < 0? 0:(pageNo * limit -1));
            List<StoreDO> storeDOS = storeMapper.selectList(new EntityWrapper<StoreDO>());
            Map<Long, String> collect = storeDOS.stream().collect(Collectors.toMap(StoreDO::getId, StoreDO::getStoreName));
            //循环赋值
            for (UserCardDO userCardDO : userCardDOList) {
                UserCardDTO userCardDTO = new UserCardDTO();
                if (userCardDO == null) continue;
                if (userCardDO.getUserId() != null && userCardDO.getUserId() > 0) {
                    UserDO userDO = userMapper.selectById(userCardDO.getUserId());
                    if (userDO != null) {
                        userCardDTO.setUserName(!StringUtils.isEmpty(userDO.getNickname())?userDO.getNickname():"");
                        userCardDTO.setPhone(!StringUtils.isEmpty(userDO.getPhone())?userDO.getPhone():"");
                    }
                }
                BeanUtils.copyProperties(userCardDO, userCardDTO);
                userCardDTO.setAdminName(cardDTO.getAdminName());
                userCardDTO.setGmtCreate(cardDO.getGmtCreate());
                userCardDTO.setStoreName(collect.get(userCardDO.getStoreId()));
                userCardDTOList.add(userCardDTO);
            }
//            cardDTO.setUserCardList(userCardDTOList);
        }
        return new Page<UserCardDTO>(userCardDTOList, pageNo, limit, count);
//        return cardDTO;
    }
}
